import requests
import json

def fetch_hk_stock_news():
    """
    从华尔街见闻API获取港股市场新闻数据并转换为Markdown格式
    """
    api_url = "https://api-one-wscn.awtmt.com/apiv1/content/lives?channel=hk-stock-channel&client=pc&limit=20&first_page=true&accept=live%2Cvip-live"
    
    try:
        response = requests.get(api_url)
        response.raise_for_status()  # 检查请求是否成功
        data = response.json()
        
        markdown = []
        if 'data' in data and 'items' in data['data']:
            for item in data['data']['items']:
                title = item.get('title', '').strip()
                content = item.get('content_text', '').strip()
                
                if title or content:
                    # 如果有标题，使用标题作为二级标题
                    if title:
                        markdown.append(f"## {title}\n")
                    # 添加内容
                    if content:
                        markdown.append(f"{content}\n")
        
        return "\n".join(markdown)
    except requests.RequestException as e:
        print(f"获取港股新闻数据时发生错误：{str(e)}")
        return ""
    except json.JSONDecodeError as e:
        print(f"解析API响应数据时发生错误：{str(e)}")
        return ""
    except Exception as e:
        print(f"处理新闻数据时发生未知错误：{str(e)}")
        return ""

if __name__ == '__main__':
    # 测试函数
    result = fetch_hk_stock_news()
    print(result)